//
//  QXRefreshControl.swift
//  QXWeibo
//
//  Created by QinXin on 15/7/2.
//  Copyright © 2015年 labi3285_Lab. All rights reserved.
//

import UIKit
import FFAutoLayout

class QXRefreshControl: UIRefreshControl {
    
    lazy var refreshView: QXRefreshView = QXRefreshView.create()
    
    override init() {
        super.init()
        
        addSubview(refreshView)
        
        refreshView.ff_AlignInner(ff_AlignType.CenterCenter, referView: self, size: CGSize(width: 150, height: 60))
        
        self.addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions(rawValue: 0), context: nil)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    var showTipFlag = false
    var loadingFlag = false
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [NSObject : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        if refreshing && !loadingFlag {
            refreshView.startLoading()
            loadingFlag = true
            return
        }
        
        if frame.origin.y < -50 && !showTipFlag {
            refreshView.rotateArrow(true)
            showTipFlag = true
        } else if frame.origin.y >= -50 && showTipFlag {
            refreshView.rotateArrow(false)
            showTipFlag = false
        }
        
    }
    
    override func endRefreshing() {
        super.endRefreshing()
        refreshView.stopLoading()
        loadingFlag = false
    }
    
    deinit {
        self.removeObserver(self, forKeyPath: "frame")
    }

}


class QXRefreshView: UIView {
    class func create() -> QXRefreshView {
        return NSBundle.mainBundle().loadNibNamed("QXRefreshView", owner: nil, options: nil).last as! QXRefreshView
    }
    
    @IBOutlet weak var loadingIconView: UIImageView!

    @IBOutlet weak var tipView: UIView!
    
    @IBOutlet weak var arrowIconView: UIImageView!
    @IBOutlet weak var messageLabel: UILabel!
    
    func rotateArrow(upWard: Bool) {
        if upWard {
            arrowIconView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
            messageLabel.text = "松手刷新"
        } else {
            arrowIconView.transform = CGAffineTransformIdentity
            messageLabel.text = "下拉刷新"
        }
        
    }
    
    func startLoading() {
        tipView.hidden = true
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        anim.toValue = M_PI * 2
        anim.repeatCount = MAXFLOAT
        anim.duration = 1.0
        loadingIconView.layer.addAnimation(anim, forKey: nil)
    }
    
    func stopLoading() {
        tipView.hidden = false
        loadingIconView.layer.removeAllAnimations()
    }
    
}
